﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Collections;

namespace HuseData
{
    public class Common
    {
        #region "在当前路径上创建日期格式目录(20060205)"
        /// <summary>
        /// 在当前路径上创建日期格式目录(20060205)
        /// </summary>
        /// <param name="sPath">目录名前辍</param>
        /// <returns>目录路径</returns>
        public static string CreateDir(string sPath)
        {
            string sTemp = System.DateTime.Today.Year.ToString() + System.DateTime.Today.Month.ToString("00") + System.DateTime.Today.Day.ToString("00");
            sPath += sTemp;
            sPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "log\\", sPath);
            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@sPath); //构造函数创建目录
            if (di.Exists == false)
            {
                di.Create();
            }

            return sPath;
        }
        #endregion

        #region 生成0-9随机数
        /// <summary>
        /// 生成0-9随机数
        /// </summary>
        /// <param name="VcodeNum">生成长度</param>
        /// <returns></returns>
        public static string RndNum(int VcodeNum)
        {
            StringBuilder sb = new StringBuilder(VcodeNum);
            Random rand = new Random();
            for (int i = 1; i < VcodeNum + 1; i++)
            {
                int t = rand.Next(9);
                sb.AppendFormat("{0}", t);
            }
            return sb.ToString();

        }
        #endregion

        #region "写文件日志"
        /// <summary>
        /// 写Billing操作日志文件
        /// </summary>
        /// <param name="input">日志内容</param>
        /// <param name="FileName">日志文件名</param>
        /// <returns>返回值true成功,false失败</returns>
        public static bool WriteFile(string input, string FileName)
        {
            bool rBool = true;
            try
            {
                string filePath;

                filePath = System.IO.Path.Combine(@CreateDir(""), DateTime.Now.ToString("yyyyMMdd") + FileName + "Log.txt");
                FileInfo logFile = new FileInfo(filePath);
                if (logFile.Exists)
                {
                    if (logFile.Length >= 800000)
                    {
                        logFile.CopyTo(filePath.Replace("Log.txt", Common.RndNum(5) + "Log.txt"));
                        File.Delete(filePath);
                    }
                }

                FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);

                StreamWriter w = new StreamWriter(fs, Encoding.UTF8);
                w.BaseStream.Seek(0, SeekOrigin.End);

                w.Write("\r\n");
                w.Write("{0}||", DateTime.Now.ToString());

                w.Write(input);
                //w.Write("\r\n");
                w.Flush();

                w.Close();

                w.Dispose();
                fs.Close();
                fs.Dispose();
            }
            catch
            {
                rBool = false;
            }
            return rBool;
        }
        #endregion


        public static bool WriteFilePath(string input, string filePath)
        {
            bool rBool = true;
            try
            {
                //filePath = System.AppDomain.CurrentDomain.BaseDirectory + filePath;
                FileInfo logFile = new FileInfo(filePath);

                FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);

                StreamWriter w = new StreamWriter(fs, Encoding.UTF8);
                w.BaseStream.Seek(0, SeekOrigin.End);
                w.Write(input);
                w.Flush();
                w.Close();
                w.Dispose();
                fs.Close();
                fs.Dispose();
            }
            catch
            {
                rBool = false;
            }
            return rBool;
        }

        #region "根据Url下载图片/文件,保存到指定目录"
        /// <summary>
        /// 根据图片Url下载图片，保存到指定目录
        /// </summary>
        /// <param name="Url">图片url</param>
        /// <param name="DIR">指定目录</param>
        /// <returns></returns>
        public static bool SaveImages_Url(string Url, string DIR)
        {
            bool bBool = false;
            WebClient wc = new WebClient();
            try
            {
                //创建目录
                System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@DIR); //构造函数创建目录
                if (di.Exists == false)
                {
                    di.Create();
                }
                string FileName = Url.Substring((Url.LastIndexOf('/') + 1), Url.Length - (Url.LastIndexOf('/') + 1));

                if (FileName.IndexOf('?') > 0)
                    FileName = Common.RndNum(5) + ".gif";
                wc.DownloadFile(System.Web.HttpContext.Current.Server.UrlPathEncode(Url), string.Format("{0}\\\\{1}", DIR, FileName));
                bBool = true;
            }
            catch (Exception ex)
            {
                WriteFile(ex.ToString(), "DownFile");
            }
            finally
            {
                wc.Dispose();
            }
            return bBool;
        }

        /// <summary>
        /// 根据Url下载图片/文件,保存到指定目录(增加下载超时限制)
        /// </summary>
        /// <param name="Url">图片/文件url</param>
        /// <param name="DIR">保存目录</param>
        /// <param name="TimeOut">超时时间(秒)</param>
        /// <returns></returns>
        public static bool SaveImages_Url(string Url, string DIR, string FileName, int TimeOut)
        {
            //创建目录
            Directory.CreateDirectory(DIR);
            return SavePhotoFromUrl(string.Format("{0}\\\\{1}", DIR, FileName), Url, TimeOut);
        }



        /// <summary>
        /// 从图片地址下载图片到本地磁盘
        /// </summary>
        /// <param name="ToLocalPath">图片本地磁盘地址</param>
        /// <param name="Url">图片网址</param>
        /// <param name="TimeOut">超时时间(秒)</param>
        /// <returns></returns>
        public static bool SavePhotoFromUrl(string FileName, string Url, int TimeOut)
        {
            bool Value = false;
            WebResponse response = null;
            Stream stream = null;

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Timeout = TimeOut * 1000;
                response = request.GetResponse();
                stream = response.GetResponseStream();

                if (!response.ContentType.ToLower().StartsWith("text/"))
                {
                    Value = SaveBinaryFile(response, FileName);

                }

            }
            catch (Exception err)
            {
                WriteFile(err.ToString(), "DownFile");
            }
            return Value;
        }

        /// <summary>
        /// Save a binary file to disk.
        /// </summary>
        /// <param name="response">The response used to save the file</param>
        // 将二进制文件保存到磁盘
        private static bool SaveBinaryFile(WebResponse response, string FileName)
        {
            bool Value = true;
            byte[] buffer = new byte[1024];

            try
            {
                if (File.Exists(FileName))
                    File.Delete(FileName);
                Stream outStream = System.IO.File.Create(FileName);
                Stream inStream = response.GetResponseStream();

                int l;
                do
                {
                    l = inStream.Read(buffer, 0, buffer.Length);
                    if (l > 0)
                        outStream.Write(buffer, 0, l);
                }
                while (l > 0);

                outStream.Close();
                inStream.Close();
            }
            catch
            {
                Value = false;
            }
            return Value;
        }

        #endregion

        #region "获取Url网页中所有图片地址"

        /// <summary>
        /// 根据网页Url获取图片Url
        /// </summary>
        /// <param name="Url">网页</param>
        /// <returns></returns>
        public static List<string> GetPage_ImgUrl(string Url)
        {
            string HostPath = Url.Substring(0, Url.LastIndexOf('/') + 1);
            return GetPageImgUrl(GetPage_Html(Url), HostPath);
        }

        /// <summary>
        /// 根据Txt获取图片url
        /// </summary>
        /// <param name="Txt">txt内容</param>
        /// <returns></returns>
        public static List<string> GetPageImgUrl(string Txt, string HostPath)
        {
            List<string> lc = new List<string>();
            ArrayList my_list = new ArrayList();
            string p = @"<img.*?>";
            Regex re = new Regex(p, RegexOptions.IgnoreCase);
            MatchCollection mc = re.Matches(Txt);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mc.Count; i++)
            {
                sb.Append(mc[i].ToString());
            }
            p = @"(?<=\bsrc=\s{0,1}).*?\s";
            //p = @"<img.*?>";

            sb.Replace('"', ' ');
            sb.Replace('>', ' ');
            string TempString = string.Empty;
            re = new Regex(p, RegexOptions.IgnoreCase);
            mc = re.Matches(sb.ToString());
            for (int i = 0; i < mc.Count; i++)
            {
                TempString = mc[i].ToString().Trim();
                if (TempString != "" && TempString.Length > 5)
                {
                    if (TempString.IndexOf("http://") < 0)
                    {
                        TempString = HostPath + TempString;
                    }
                    lc.Add(TempString);
                }

            }
            return lc;
        }
        #endregion

        #region "获取Url网页中所有链接网址"
        /// <summary>
        /// 获取Url网页中所有链接网址
        /// </summary>
        /// <param name="Url">网址</param>
        /// <returns></returns>
        public static List<string> GetPage_Url(string Url)
        {
            return GetTxtUrl(GetPage_Html(Url));
        }

        /// <summary>
        /// 获取Txt中的url列表
        /// </summary>
        /// <param name="Txt">Txt内容</param>
        /// <returns></returns>
        public static List<string> GetTxtUrl(string Txt)
        {
            List<string> lc = new List<string>();
            ArrayList my_list = new ArrayList();
            string p = @"http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?";
            Regex re = new Regex(p, RegexOptions.IgnoreCase);
            MatchCollection mc = re.Matches(Txt);
            for (int i = 0; i < mc.Count; i++)
            {
                lc.Add(mc[i].ToString());
            }
            return lc;
        }
        #endregion

        #region "根据网址获取网页内容"
        /// <summary>
        /// 根据网址获取网页内容
        /// </summary>
        /// <param name="Url">网址</param>
        /// <returns></returns>
        public static string GetPage_Html(string Url)
        {
            string TempHtml = "";
            WebClient wc = new WebClient();
            try
            {
                Byte[] pageData = wc.DownloadData(Url);
                TempHtml = Encoding.Default.GetString(pageData);  //如果获取网站页面采用的是GB2312，则使用这句              
                //string pageHtml = Encoding.UTF8.GetString(pageData); //如果获取网站页面采用的是UTF-8，则使用这句
            }
            catch (Exception ex)
            {
                WriteFile(ex.ToString(), "DownFile");
            }
            finally
            {
                wc.Dispose();
            }
            return TempHtml;
        }
        #endregion
    }

    /// <summary>
    /// 报表类型
    /// </summary>
    public enum ReportDateType
    { 
            Day=0,
            Week=1,
            Month=2
    }
}
